<script setup>
import VIcon from "@/components/icon/VIcon.vue";
import {onMounted, ref} from "vue";
import {getPrevAndNextArticle} from "@/api/article.js";
import {useRouter} from "vue-router";

const $router = useRouter();

const props = defineProps({
  id: {
    type: [Number, String],
    default: undefined
  }
});

onMounted(() => {
  if (!props.id) {
    return;
  }
  findPrevNextArticle(props.id);
});
const loading = ref(true);
const article = ref({
  prev: null,
  next: null
});
const findPrevNextArticle = (id) => {
  loading.value = true;
  getPrevAndNextArticle(id).then(res => {
    article.value = res.data;
    loading.value = false;
  }).catch(err => {
    console.log(err);
    loading.value = false;
  });
};

const readArticle = (id) => {
  if (!id) return;
  $router.push({path: `/article/read/${id}`});
};
</script>

<template>
  <div class="v-prev-last-article" v-loading="loading" v-if="article?.prev || article?.next">
    <div class="v-prev-article" @click="readArticle(article?.prev?.id)">
      <template v-if="article?.prev">
        <span><v-icon icon="ArrowLeftBold"/>上一篇</span>
        <span>{{ article?.prev?.title }}</span>
      </template>
    </div>
    <div class="v-last-article" @click="readArticle(article?.next?.id)">
      <template v-if="article?.next">
        <span>下一篇<v-icon icon="ArrowRightBold"/></span>
        <span>{{ article?.next?.title }}</span>
      </template>
    </div>
  </div>
</template>

<style scoped>
.v-prev-last-article {
  margin: 10px 0;
  padding: 10px 20px;
  box-sizing: border-box;
  border-radius: 4px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #ffffff;
  
  > div:hover {
    background-color: rgba(0, 0, 0, 0.05);
    cursor: pointer;
    transition: all 0.3s;
    border-radius: 4px;
    
    > span:nth-child(2) {
      color: #409EFF;
      text-decoration: underline;
    }
  }
  
  > div {
    width: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding: 20px 0;
    box-sizing: border-box;
    
    > span:nth-child(1) {
      font-size: 18px;
      color: rgba(0, 0, 0, 0.8);
      font-weight: bold;
    }
    
    > span:nth-child(2) {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      padding: 0 10px;
      box-sizing: border-box;
    }
  }
  
  .v-prev-article {
    padding-right: 40px;
    
    > span:nth-child(1) {
      display: flex;
      align-items: center;
      justify-content: flex-start;
    }
  }
  
  .v-last-article {
    text-align: right;
    padding-left: 40px;
    
    > span:nth-child(1) {
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
</style>